<?php

namespace app\api\model;

use think\Model;

class ExaminationPaper extends Model
{
    public static function getExaminationInfoById($examinationId)
    {
        return self::alias('a')
            ->join('examination_category ec', 'ec.id = a.cid')
            ->field('a.*,ec.title as category_title')
            ->where('a.id', $examinationId)
            ->find();
    }

    public static function getListByWhere($where, $pageNo, $pageSize)
    {
        return self::alias('a')
            ->join('examination_category ec', 'ec.id = a.cid')
            ->field('a.*,ec.title as category_title')
            ->page($pageNo, $pageSize)
            ->where($where)
            ->select()
            ->toArray();
    }

    public static function getDailyExamination()
    {
        $exam = self::where('cid', 1)
            ->where('create_time', '>', strtotime(date('Y-m-d')))
            ->find();
        if (!$exam) {
            //脚本执行
            $examId = self::insertGetId([
                'cid' => 1,
                'title' => '每日挑战',
                'thumb' => '/upload/image/20250624/1169a36a05f9a573a9bddb96d5e95fe5.jpg',
                'answer_time' => 8,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            //单选
            $question1 = QuestionsList::field('id')->where('type', 1)->orderRaw('rand()')->limit(10)->select()->toArray();
            foreach ($question1 as $v) {
                ExaminationQuestion::insert([
                    'pid' => $examId,
                    'qid' => $v['id'],
                    'score' => 4,
                    'create_time' => time(),
                ]);
            }
            //判断
            $question2 = QuestionsList::field('id')->where('type', 3)->orderRaw('rand()')->limit(10)->select()->toArray();
            foreach ($question2 as $v) {
                ExaminationQuestion::insert([
                    'pid' => $examId,
                    'qid' => $v['id'],
                    'score' => 4,
                    'create_time' => time(),
                ]);
            }
            //多选
            $question3 = QuestionsList::field('id')->where('type', 2)->orderRaw('rand()')->limit(5)->select()->toArray();
            foreach ($question3 as $v) {
                ExaminationQuestion::insert([
                    'pid' => $examId,
                    'qid' => $v['id'],
                    'score' => 4,
                    'create_time' => time(),
                ]);
            }
        }
        return $exam['id'] ?? $examId;
    }
}